<?php

namespace App\Models\Goods;

use App\Models\Goods\GoodsSpecGroup;

use Illuminate\Database\Eloquent\Model;

class GoodsSpecRelation extends Model
{

    protected $table = 'goods_spec_relation';

    protected $primaryKey = 'mainPostID';

    public $timestamps = false;

    public $incrementing = false;

    
    /**
     * 根据主商品号查询商品规格
     * @param int $mainPostID 主商品网购号
     * @return array
     */
    public static function getList($mainPostID)
    {

        if(!isset( $mainPostID ) || !ebsig_is_int( $mainPostID)) {
            return [];
        }

        $goods_spec = self::where('mainPostID', $mainPostID)->orderBy('sort', 'ASC')->get()->toArray();
        if( !$goods_spec ) {
            return [];
        }

        $return_array = array();

        foreach ( $goods_spec as &$item ) {

            $spec_group_id = $item['specGroupID'];
            $spec_id = $item['specID'];

            //查询规格组，判断规格等级
            $spec_group_data = GoodsSpecGroup::find($spec_group_id)->toArray();

            $sort = !empty($spec_group_data) && $spec_group_data['isColor'] == 1 ? 0 : 1;

            if ( !array_key_exists($sort, $return_array) ) {
                $return_array[$sort] = [
                    'id' => $spec_group_id,
                    'name' => $item['specGroupName'],
                    'list' => []
                ];
            }
            $return_array[$sort]['list'][$spec_id] = [
                'id' => $spec_id,
                'name' => $item['specName']
            ];

        }

        return $return_array;

    }


}
